<?php
namespace ImiApp\WebSocketServer\Controller;

// use Imi\ConnectContext;
// use Imi\Controller\WebSocketController;
// use Imi\Server\Route\Annotation\WebSocket\WSRoute;
// use Imi\Server\Route\Annotation\WebSocket\WSAction;
use Imi\Server\Route\Annotation\WebSocket\WSController;
// use Imi\Server\Route\Annotation\WebSocket\WSMiddleware;

// use Imi\Server\Route\Annotation\WebSocket\WSConfig;


use Imi\Db\Db;
// use Imi\Pool\BasePool;

/**
 * 用户表
 * @WSController
 */
class User 
{
    
    public $uid;
    public function __construct($uid = null) {
        if($this->is_uid_pd($uid)){
            $this->uid = $uid;
        }else{
            return false;
        }
    }


    /* 
    * 是否是用户判断
    */     
    public function is_uid_pd($uid=null)
    {   
        //非纯数字
        if(!is_numeric($uid)){
            $uid = $this->uid_decode($uid);
        }

        if($uid){
            $db = Db::query();
            $user = $db->table('wst_user')->where('id','=',$uid)->select()->get();
            // var_dump($user);
            if($user){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }    
    }

    /* 
    * 是否是用户
    */
    public function is_uid()
    {
        if(empty($this->uid)){
            return false;
        }else{
            return true;
        }
    }

    

    /* 
    * 修改用户在线状态
    */     
    public function online($uid=null,$online = '2')
    {
        if(!$uid){
            $uid = $this->uid;
        }
        $db = Db::query();
        $res = $db->table('wst_user')->where('id','=',$uid)->update(['on_line'=>$online,'logintime'=>time()]);
        return $res;
    }

    
    /* 
    * 修改用户在线状态
    */     
    public function offline($uid=null,$online = '2')
    {
        if(!$uid){
            $uid = $this->uid;
        }
        $db = Db::query();
        $res = $db->table('wst_user')->where('id','=',$uid)->update(['on_line'=>$online,'logintime'=>time()]);
        return $res;
    }

    /* 
    * 修改用户信息
    */  
    public function update_data($uid=null,$data = array()){
        if(!$uid){
            $uid = $this->uid;
        }
        $db = Db::query();
        $res = $db->table('wst_user')->where('id','=',$uid)->update($data);
        return $res;
    }


    public function uid_decode($uid_str)
    {
        // return base64_decode($uid_str);
        $data = json_decode(base64_decode(substr($uid_str, 2)),true);
        if($data){
            $uid = $data['uid'];
        }else{
            $uid = null;
        }
        return $uid;
    }


}